#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>

void writer(int wfd)
{
    const char* str = "hello father,i am child";
    char buff[128];
    int cnt = 0;
    while(1)
    {
        snprintf(buff,sizeof(buff),"message:%s count:%d pid:%d\n",str,cnt++,getpid());
        write(wfd,buff,strlen(buff));
        sleep(1);
    }
}

void reader(int rfd)
{
    char buff[1024];
    while(1)
    {
        ssize_t n  = read(rfd,buff,sizeof(buff)-1);
        
        printf("father get message:%s",buff);
    }
}

int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if(n<0) return 1;
    printf("pipefd[0]:%d,pipefd[1]:%d\n",pipefd[0],pipefd[1]);

    pid_t id = fork();
    if(id == 0)
    {
        //pipefd[0]:read    pipefd[1]:write
        close(pipefd[0]);
        writer(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);
    reader(pipefd[0]);

    wait(NULL);
    

    return 0;
}

